//
//  XWJChangeSoureVC.swift
//  DZMeBookRead
//
//  Created by fox on 2017/8/29.
//  Copyright © 2017年 DZM. All rights reserved.
//

import UIKit
/*
    切换源数据章节
 // 范例
 http://api.zhuishushenqi.com/atoc?view=summary&book=51d11e782de6405c45000068
 
 请求切换源后的目录
 http://api.zhuishushenqi.com/btoc/56f28f3ed1f822614cff4460?view=chapters
 
 old之前请求源的数据
http://api.zhuishushenqi.com/mix-atoc/5224a6db3d25dae84b0003a8?bookId=5224a6db3d25dae84b0003a8
 
 
 两个章节请求的URL不一样
 
 */
let identifiercell = "ChangeSoureVCidentifiercell"
let defultIndetifier = "defultIndetifier"
class XWJChangeSoureVC: XYViewController {

    
    var cellSeleRow:Int = -1
    
    
    var soureArray:[ChangeSoureModel] = []
    let navView = UIView()
    let textlab = UILabel()
    let rigthBtn = UIButton()
    let bookID:String

    var tableView:UITableView!
    var defultImage = UIImageView()
     init(bookID: String) {
        self.bookID = bookID
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadData()
        
    }
    
    func loadData() {
        //  http://api.zhuishushenqi.com/atoc?view=summary&book=51d11e782de6405c45000068
        
//        HUDManager.xwj_show()
        let dict = ["view":"summary","book":bookID]

        let url = BaseUrl.defult.rawValue + "atoc"
        HTTPManager.requestModel(url: url, method: .get, parameters: dict, iscaChe: false) { (resp:SoureModel?, error) in
//            HUD.hide()
            if let resp = resp {
                if resp.array.count == 0 {
                    self.tableView.isHidden = true
                    self.defultImage.isHidden = false
                    return
                }
        
                self.soureArray = resp.array
                self.tableView.reloadData()
            }
            
            if error != nil {
//                XWJLog(messsage: "error有值?")
                self.tableView.isHidden = true
                self.defultImage.isHidden = false
            }
            
        }
    }
    
    override func viewDidLayoutSubviews(){
        super.viewDidLayoutSubviews()
        tableView.frame = CGRect.init(x: 0, y: 64, width: ScreenWidth, height: ScreenHeight - 64)
        navView.frame = CGRect.init(x: 0, y: 0, width: ScreenWidth, height: 64)
        textlab.frame = CGRect.init(x: 0, y: 24, width: 80, height: 24)
        textlab.centerX = navView.centerX
        rigthBtn.frame = CGRect.init(x:  ScreenWidth - 60, y: 24, width: 60, height: 24)
        defultImage.frame = tableView.frame
    }
    
    
    func setupUI() {
        
        navView.backgroundColor = UIColor.white
        rigthBtn.setImage(UIImage.init(named: "actionbar_close"), for: .normal)
        textlab.text = "选择来源"
        textlab.textColor = UIColor.black
        textlab.textAlignment = .center
        navView.addSubview(textlab)
        navView.addSubview(rigthBtn)
        rigthBtn.addTarget(self, action: #selector(clickdismiss), for: .touchUpInside)
        view.addSubview(navView)
        tableView = UITableView.init(frame: CGRect.zero, style: .grouped)
        view.addSubview(tableView)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(XWJChangeSoureCell.self, forCellReuseIdentifier: identifiercell)
        tableView.register(XWJChageSoureDefultCell.self, forCellReuseIdentifier: defultIndetifier)
        view.addSubview(defultImage)
        defultImage.isHidden = true
        
        let soureStr = String.init(format: "%@ChangeSoure", bookID)
        let contain =  HTTPCache.xwj_containsObject(forKey: soureStr)
        if contain == true {
            let indexPathRowStr = HTTPCache.xwj_objectForKey(forkey: soureStr)as! String
           cellSeleRow = indexPathRowStr.integerValue()
        }
        view.addSubview(defultImage)
        defultImage.isHidden = true
    }
    
    deinit {
//        XWJLog(messsage: "我是切换源目录死了")
    }
    func clickdismiss() {
        dismiss(animated: true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    

   
}
extension XWJChangeSoureVC:UITableViewDelegate,UITableViewDataSource {
     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
     
        var idString = soureArray[indexPath.row].id
        if indexPath.row == 0 {
            idString = bookID
        }else {
            /// MARK :  -当获取源使用
            let soureStrBookID = String.init(format: "%@ChangeSoureBookID", bookID)
            HTTPCache.xwj_setObject(object: idString as NSCoding, forKey: soureStrBookID)
        }
        
        /// 发送一条通知给MianVC 
        let notificationName = Notification.Name(rawValue: changeSoureNotificationKey)
        let dict = ["currenKey":indexPath.row,"id":idString] as [String : Any]
       
        NotificationCenter.default.post(name: notificationName, object: self, userInfo: dict)
        
        /// 当作显示当前选中使用
        let soureStr = String.init(format: "%@ChangeSoure", bookID)
        HTTPCache.xwj_setObject(object: String(indexPath.row) as NSCoding, forKey: soureStr)
       
       
        
        clickdismiss()
    }
    
     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.soureArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 44
        }
        return 80
    }
    
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 
        
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: defultIndetifier, for: indexPath)as! XWJChageSoureDefultCell
            if indexPath.row == cellSeleRow {
                cell.currenSele.isHidden = false
            }
            
            return cell
        }
  
        let cell = tableView.dequeueReusableCell(withIdentifier: identifiercell, for: indexPath) as! XWJChangeSoureCell
        cell.model = soureArray[indexPath.row]
        cell.accessoryType = .disclosureIndicator
        if indexPath.row == cellSeleRow {
            cell.currenSele.isHidden = false
        }
        return cell
    }
}
